﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccessLayer;
using DataAccessLayer.DAL;
using Common;
using System.Threading;
using System.Net.Mail;
using System.IO;

namespace BestBuy.SellerViews
{
    public partial class SellerBid : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            User user =UserDAL.GetUserByUsername(HttpContext.Current.User.Identity.Name);
            Auction auction = null;
            if (Request.QueryString["AuctionID"] != null)
            {
                int id = int.Parse(Request.QueryString["AuctionID"]);
                auction = AuctionDAL.GetAuctionByID(id);
            }
            if (!IsPostBack)
            {
                LoadAuctionDetail(auction);
            }
            TimeCountDown(user, auction); // dem so luong thoi gian con lai
            LoadBestCost(auction); //danh sach seller dua ra gia thap nhat
            LoadBidDetail(auction); // danh sach dau gia
            LoadQuestion(auction); // danh sach cau hoi va cau tra loi
            LoadBookmark(user, auction); //neu user da bookmark auction nay thi btnbookmark hide, else btn visible
            LoadSelectSellerPanel(user);
        }

        private void LoadSelectSellerPanel(User user)
        {
            if (user != null)
            {
                if (user.RoleID == (int)RoleType.Buyer)
                {
                    pnSelectWonSeller.Visible = true;
                }
            }
        }

        private void TimeCountDown(User user, Auction auction)
        {
            if (auction != null)
            {
                Timer.CountDown(auction.EndTime);
                DateTime now = DateTime.Now;
                DateTime end = auction.EndTime;
                if (end > now)
                {
                    if (user != null)
                    {
                        if (user.RoleID == (int)RoleType.Seller)
                            pnSellerBid.Visible = true;
                    }
                }
                //Thoi gian ket thuc auctiontion
                string closingdate = string.Format("{0} at {1}", auction.EndTime.ToLongDateString(), auction.EndTime.ToShortTimeString());
                lbClosingDate.Text = closingdate;
            }
        }

        private void LoadBookmark(User user, Auction auction)
        {
            if (user != null)
            {
                if (auction != null)
                {
                    if (UserDAL.GetFollowAuctionByID(user.ID, auction.ID) == null)
                    {
                        btnBookmark.Visible = true;
                    }
                }
            }
        }

        private void LoadBidDetail(Auction auction)
        {
            if (auction != null)
            {
                gvAuctionDetail.DataSource = SellerBidDAL.GetBids(auction.ID);
                gvAuctionDetail.DataBind();
            }            
        }

        private void LoadQuestion(Auction auction)
        {
            if (auction != null)
            {
                Auction auc = AucQuestionAnswer.GetAllQuestionByAucID(auction.ID);
                gvComment.DataSource = auc.AuctionQuestionAnswers;
                gvComment.DataBind();
            }
        }

        protected void gvComment_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataAccessLayer.User user = (DataAccessLayer.User)DataBinder.Eval(e.Row.DataItem, "User");
                if (user != null)
                {
                    Label userNameLabel = e.Row.FindControl("UsernameLabel") as Label;
                    Label lbReplyDate = e.Row.FindControl("lbReplyDate") as Label;
                    Label lbAnswer = e.Row.FindControl("lbAnswer") as Label;
                    if (userNameLabel != null)
                    {
                        userNameLabel.Text = user.Username;
                    }
                    if (lbReplyDate != null)
                    {
                        
                    }
                }
            }
        }

        private void LoadAuctionDetail(Auction auction)
        {
            if (auction != null)
            {
                hidAuctionID.Value = auction.ID.ToString();
                User userCreated = UserDAL.GetUser(auction.CreateByUserID);
                if (userCreated != null)
                {
                    lbUsername.Text = userCreated.Username;
                }
                lbTitle.Text = auction.Title;
                lbLookingFor.Text = auction.Subtile;
                lbQuantity.Text = auction.Quantity.ToString();
                lbQuantity1.Text = lbQuantity.Text;
                lbStartPrice.Text = auction.StartPrice.ToString();
                lbDescription.Text = auction.Description;
            }
        }

        private void LoadBestCost(Auction auction)
        {
            if (auction != null)
            {
                gvListBestBid.DataSource = SellerBidDAL.GetBestCost(auction.ID);
                gvListBestBid.DataBind();
            }
        }

        private void SendEmail(string emailAdds, string subject,string content)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();
                mailMsg.Subject = subject;
                mailMsg.To.Add(emailAdds);
                mailMsg.IsBodyHtml = true;
                string htmlBody = content;
                mailMsg.Body = htmlBody;
                SmtpClient smtp = new SmtpClient();
                smtp.Send(mailMsg);
            }
            catch
            {
            }
        }

        protected void txtPerItem_TextChanged(object sender, EventArgs e)
        {
            txtTotalBid.Text = string.Empty;
            int amount = 0;
            int.TryParse(txtPerItem.Text, out amount);
            if (amount > 0)
            {
                txtTotalBid.Text = (int.Parse(txtPerItem.Text) * int.Parse(lbQuantity1.Text)).ToString();
            }
        }

        protected void btnBid_Click(object sender, EventArgs e)
        {
            try
            {
                decimal cost = 0;
                decimal.TryParse(txtTotalBid.Text.ToString(), out cost);
                int auctionID = 0;
                int.TryParse(hidAuctionID.Value, out auctionID);
                Auction auc = AuctionDAL.GetAuctionByID(auctionID);
                if (auc != null && cost > 0)
                {
                    DataAccessLayer.SellerBid bid = new DataAccessLayer.SellerBid();
                    bid.AuctionID = int.Parse(hidAuctionID.Value);
                    bid.BidValue = cost;
                    bid.BidDate = DateTime.Now;
                    bid.Description = txtDescription.Text;
                    String username = HttpContext.Current.User.Identity.Name;
                    if (username != string.Empty)
                    {
                        SellerBidDAL.AddBid(username, bid);
                        SellerBidMessage.Show("Bid success.", UserControls.MessagePanel.MessageType.Success);
                        txtPerItem.Text = txtTotalBid.Text = string.Empty;
                    }

                    // Send email to Buyer created
                    User buyer = UserDAL.GetUser(auc.CreateByUserID);
                    Thread sendmailThread = new Thread(delegate()
                    {
                        string subject = "Seller bid in your auction";
                        string content = string.Format("Seller bid your item with cost {0}. Description: {1}",bid.BidValue,bid.Description);
                        SendEmail(buyer.Email, subject, content);
                    });
                    sendmailThread.IsBackground = true;
                    sendmailThread.Start();
                }
                Response.Redirect(Request.RawUrl);
            }
            catch
            {
                SellerBidMessage.Show("Bid error.", UserControls.MessagePanel.MessageType.Error);
            }
        }

        protected void txtDescription_TextChanged(object sender, EventArgs e)
        {

        }

        protected void btnPostComment_Click(object sender, EventArgs e)
        {
            string sellername = HttpContext.Current.User.Identity.Name;
            if (sellername == string.Empty || txtComment.Text == string.Empty)
                return;
            if (Request.QueryString["AuctionID"] != null)
            {
                User buyer = null;
                Auction auction = null;
                int sellerID = UserDAL.GetUserIDByUsername(sellername);
                AuctionQuestionAnswer comment = new AuctionQuestionAnswer();
                int id = int.Parse(Request.QueryString["AuctionID"]);
                auction = AuctionDAL.GetAuctionByID(id);
                comment.SellerID = sellerID;
                comment.AuctionID = id;
                comment.Question = txtComment.Text;
                comment.OnDate = DateTime.Now;
                AucQuestionAnswer.AddComment(comment);

                buyer = UserDAL.GetUser(auction.CreateByUserID);
                if (buyer.UserReference.NotifyNewBid)
                {
                    Thread sendmailThread = new Thread(delegate()
                    {
                        string subject = "Seller has question in your auction";
                        string content = string.Format("Hi frinend! I give you some question. {0}", comment.Question);
                        SendEmail(buyer.Email, subject, content);
                    });
                    sendmailThread.IsBackground = true;
                    sendmailThread.Start();
                }
            }
            Response.Redirect(Request.RawUrl);
        }

        protected void btnBookmark_Click(object sender, EventArgs e)
        {
            User user =UserDAL.GetUserByUsername(HttpContext.Current.User.Identity.Name);
            if (user != null)
            {
                if (Request.QueryString["AuctionID"] != null)
                {
                    int id = int.Parse(Request.QueryString["AuctionID"]);
                    FollowAuction follow = new FollowAuction { AuctionID = id, SellerID = user.ID, OnDate = DateTime.Now };
                    UserDAL.AddFollowAuction(follow);
                    Response.Redirect(Request.RawUrl);
                }
            }
        }

        protected void btnSelectSeller_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["AuctionID"] != null)
            {
                int id = int.Parse(Request.QueryString["AuctionID"]);
                Response.Redirect(string.Format("~/BuyerViews/SelectWonSeller.aspx?AuctionID={0}", id.ToString()));
            }
           
        }
    }
}